//获取应用实例
const app = getApp();
const request = require('../../../utils/request.js');
const config = require('../../../utils/config.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorTheme: app.globalData.colorTheme,
    imgList: [],
    regionList: [],
    schoolList: [],
    yearList: [],
    imgBase64List: [],
    roleList: [{
        id: 1,
        name: "学生"
      },
      {
        id: 2,
        name: "导师"
      },
      {
        id: 4,
        name: "活动主办方"
      },
    ],
    degreeList: [{
        id: 1,
        name: '专科'
      },
      {
        id: 2,
        name: '本科'
      },
      {
        id: 3,
        name: '博士及以上'
      }
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载ing'
    });
    let that = this;
    let url = config.SERVER_URL + 'area/0/child';
    // 初始化省份选择信息
    request.requestGetApi(url, {}, {}, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        this.setData({
          regionList: res.data
        });
      };
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    })
    // 初始化年份(年级)选择信息
    let now = new Date();
    let startYear = now.getFullYear() - 30;
    let endYear = now.getFullYear() + 30;
    let yearList = [];
    for (let i = startYear; i <= endYear; i++) {
      yearList.push(i);
    }
    this.setData({
      yearList: yearList
    });
  },

  /**
   * 地址选择变化
   */
  regionChange: function(e) {
    let that = this;
    let index = e.detail.value;
    let regionId = this.data.regionList[index].id;
    console.log(index);
    this.setData({
      regionIndex: index,
      regionId: regionId
    });
    // 加载对应省下的校园数据
    wx.showLoading({
      title: '加载ing'
    });
    let url = config.SERVER_URL + 'area/school/' + regionId
    request.requestGetApi(url, {}, {}, 'application').then(res=>{
      if (res.status === config.STATUS_OK) {
        this.setData({
          schoolList: res.data
        });
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    })
  },

  
  /**
   * 学校选择变化
   */
  schoolChange: function(e) {
    let index = e.detail.value;
    let schoolId = this.data.schoolList[index].id;
    this.setData({
      schoolIndex: index,
      schoolId: schoolId
    });
  },

  /**
   * 角色选择变化
   */
  roleChange: function(e) {
    let index = e.detail.value;
    let roleId = this.data.roleList[index].id;
    this.setData({
      roleIndex: index,
      roleId: roleId
    });
  },

  /**
   * 年级选择变化
   */
  yearChange: function(e) {
    let index = e.detail.value;
    this.setData({
      yearIndex: index,
      grade: this.data.yearList[index]
    });
  },

  /**
   * 学位选择变化
   */
  degreeChange: function(e) {
    let index = e.detail.value;
    let degreeId = this.data.degreeList[index].id;
    this.setData({
      degreeId: degreeId,
      degreeIndex: index
    });
  },

  /**
   * 表单提交
   */
  submitApply: function(e) {
    let params = e.detail.value;
    // 校验表单参数
    let res = this.checkForm(params);
    if (res) {
      wx.showModal({
        title: '提示',
        content: res,
      })
      return;
    }
    let imageList = this.data.imgList;
    // 图片转base64
    const credentialsPhotoFront = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(imageList[0], 'base64');
    const credentialsPhotoReverse = 'data:image/jpg;base64,'+ wx.getFileSystemManager().readFileSync(imageList[1], 'base64');
    let realSize1 = credentialsPhotoFront.length - (credentialsPhotoFront.length/8)*2;
    let realSize2 = credentialsPhotoReverse.length - (credentialsPhotoReverse.length/8)*2;
    // 限制文件大小不超过10Mb
    if (realSize1 > app.uploadFileMaxSize || realSize2 > app.uploadFileMaxSize){
      wx.showModal({
        title: '错误',
        content: '单张图片不得超过10Mb',
      });
      return;
    }
    params['credentialsPhotoFront'] = credentialsPhotoFront;
    params['credentialsPhotoReverse'] = credentialsPhotoReverse;
    console.log(params);
    let url = config.SERVER_URL + 'user/applyForCertification';
    let token = wx.getStorageSync('token');
    let that = this;
    wx.showLoading({
      title: '提交申请ing'
    });
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 1500
        });
        setTimeout(()=>{
          wx.navigateBack({
            delta: 1
          });
        }, 500);
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        });
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    })
  },

  /**
   * 表单参数校验
   */
  checkForm: function(params){
    if (!params.schoolId){
      return '请选择学校';
    }
    if (!params.degreeId) {
      return '请选择学历';
    }
    if (!params.areaId) {
      return '选择省份';
    }
    if (!params.role) {
      return '请选择角色';
    }
    if (!params.grade) {
      return '请选择年级';
    }
    if (!params.subject) {
      return '请填写专业';
    }
    if (!params.realName) {
      return '请填写真实姓名';
    }
    if (this.data.imgList.length < 2){
      return '正、反面照都需要上传';
    }
    if (!params.isAgree){
      return '必须同意协议/条款'
    }
  },

  ChooseImage() {
    wx.chooseImage({
      count: 2, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择或直接拍照
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },

  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除材料',
      content: '确定要删除吗？',
      cancelText: '取消',
      confirmText: '删除',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList,
          })
        }
      }
    })
  }
})